<template>
  <div class="booking-system">
    <!-- 顶部标题栏 -->
    <div class="header-bar">
      <h1>展馆预约</h1>
    </div>

    <!-- 页面内容区域 -->
    <div class="content-area" :class="{ 'no-bottom-nav': currentTab === 'details' || currentTab === 'ticket' || currentTab === 'personalInfo' }">
      <component 
        :is="currentComponent" 
        @switchTab="switchTab" 
        @showBookingDetails="handleShowBookingDetails"
        @showBookingDetailsFromProfile="handleShowBookingDetailsFromProfile"
        @savePersonalInfo="handleSavePersonalInfo"

        :bookingData="bookingData"
        :bookingRecords="bookingRecords"
        :fromProfile="fromProfile"
        :selectedTimeSlot="selectedTimeSlot"
        @goBack="handleGoBack"
        @save="handlePersonalInfoSave"
        @cancel="handlePersonalInfoCancel"
      />
    </div>

    <!-- 加载组件 -->
    <LoadingSpinner 
      :visible="isLoading" 
      :title="loadingTitle" 
      :message="loadingMessage" 
    />

    <!-- 底部导航栏 -->
    <div class="bottom-navigation" v-show="currentTab !== 'details' && currentTab !== 'ticket' && currentTab !== 'personalInfo'">
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'home' }"
        @click="switchTab('home')"
      >
        <div class="nav-icon">🏠</div>
        <div class="nav-text">首页</div>
      </div>
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'gallery' }"
        @click="switchTab('gallery')"
      >
        <div class="nav-icon">🎫</div>
        <div class="nav-text">展馆预约</div>
      </div>
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'merchandise' }"
        @click="switchTab('merchandise')"
      >
        <div class="nav-icon">🛍️</div>
        <div class="nav-text">展馆周边</div>
      </div>
      <div 
        class="nav-item" 
        :class="{ active: currentTab === 'profile' }"
        @click="switchTab('profile')"
      >
        <div class="nav-icon">👤</div>
        <div class="nav-text">我的</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import BookingHome from '../components/BookingHome.vue'
import BookingProfile from '../components/BookingProfile.vue'
import BookingGallery from '../components/BookingGallery.vue'
import BookingTicket from '../components/BookingTicket.vue'
import BookingDetails from '../components/BookingDetails.vue'
import BookingMerchandise from '../components/BookingMerchandise.vue'
import PersonalInfoForm from '../components/PersonalInfoForm.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import { getUserStore } from '../stores/user'
import { getUserBookings } from '../api/booking.js'
import { ElMessage } from 'element-plus'

// 当前选中的标签页
const currentTab = ref('home')

// 预约数据
const bookingData = ref({})

// 预约记录列表
const bookingRecords = ref([])

// 选中的时间段数据
const selectedTimeSlot = ref(null)

// 保存的个人信息
const savedPersonalInfo = ref(null)

// 加载状态
const isLoading = ref(false)
const loadingTitle = ref('加载中')
const loadingMessage = ref('请稍候，正在为您准备精彩内容...')

// 显示加载
const showLoading = (title = '加载中', message = '请稍候，正在为您准备精彩内容...') => {
  loadingTitle.value = title
  loadingMessage.value = message
  isLoading.value = true
}

// 隐藏加载
const hideLoading = () => {
  isLoading.value = false
}

// 组件映射
const componentMap = {
  home: BookingHome,
  gallery: BookingGallery,
  ticket: BookingTicket,
  merchandise: BookingMerchandise,
  profile: BookingProfile,
  details: BookingDetails,
  personalInfo: PersonalInfoForm,
}

// 当前显示的组件
const currentComponent = computed(() => {
  return componentMap[currentTab.value]
})

// 切换标签页
const switchTab = (tab, data = null) => {
  // 显示加载
  showLoading('页面切换中', '正在为您加载内容...')
  
  // 模拟加载延迟
  setTimeout(() => {
    currentTab.value = tab
    // 如果有数据传递，可以在这里处理
    if (data) {
      console.log('Received data:', data)
      // 可以通过provide/inject或其他方式传递数据给子组件
    }
    hideLoading()
  }, 800)
}

// 处理显示预约详情（从预约页面）
const handleShowBookingDetails = (data) => {
  showLoading('预约处理中', '正在生成您的预约详情...')
  
  setTimeout(async () => {
    bookingData.value = data
    previousTab.value = 'home'
    
    // 重新加载预约记录，确保数据同步
    await loadUserBookings()
    
    currentTab.value = 'details'
    hideLoading()
  }, 1200)
}

// 处理显示预约详情（从我的页面）
const handleShowBookingDetailsFromProfile = (data) => {
  bookingData.value = data
  previousTab.value = 'profile'
  currentTab.value = 'details'
}

// 记录从哪个页面跳转到详情页的
const previousTab = ref('home')

// 是否从我的页面跳转过来
const fromProfile = computed(() => previousTab.value === 'profile')

// 处理返回操作
const handleGoBack = () => {
  currentTab.value = previousTab.value
}



// 处理个人信息保存成功
const handlePersonalInfoSave = (personalInfo) => {
  console.log('✅ 个人信息保存成功:', personalInfo)
  savedPersonalInfo.value = personalInfo
  
  // 返回到预约页面
  currentTab.value = 'ticket'
}

// 处理个人信息表单取消
const handlePersonalInfoCancel = () => {
  console.log('❌ 取消个人信息填写')
  currentTab.value = 'ticket'
}

// 处理保存个人信息（兼容旧接口）
const handleSavePersonalInfo = (personalInfo) => {
  handlePersonalInfoSave(personalInfo)
}

// 获取用户状态管理器
const userStore = getUserStore()

// 加载用户预约记录
const loadUserBookings = async () => {
  const token = userStore.userToken.value
  if (!token || typeof token !== 'string') {
    console.log('ℹ️ userToken无效，无法加载预约记录')
    return
  }

  try {
    console.log('🔍 正在加载用户预约记录...')
    const response = await getUserBookings(token)
    
    if (response.code === 200 && response.data) {
      // 转换后端数据格式为前端格式
      const bookings = response.data.map(booking => {
        // 根据数据库结构映射字段
        const bookingDate = booking.bookingDate || booking.booking_date
        const startTime = booking.bookingTimeStart || booking.booking_time_start
        const endTime = booking.bookingTimeEnd || booking.booking_time_end
        const contactName = booking.contactName || booking.contact_name
        const contactPhone = booking.contactPhone || booking.contact_phone
        const bookingNumber = booking.bookingNumber || booking.booking_number
        
        // 格式化时间显示
        const formatTime = (timeStr) => {
          if (typeof timeStr === 'string') {
            return timeStr.slice(0, 5) // 取前5位 HH:MM
          }
          return timeStr
        }
        
        // 状态映射
        const statusMap = {
          'confirmed': 'confirmed',
          'completed': 'completed', 
          'no_show': 'cancelled'
        }
        
        // 解析notes字段中的个人信息
        const notes = booking.notes || ''
        const genderMatch = notes.match(/性别：([^，]+)/)
        const ageMatch = notes.match(/年龄：([^，]+)/)
        const educationMatch = notes.match(/学历：([^，]+)/)
        
        // 解析specialRequirements字段中的职业信息
        const specialRequirements = booking.specialRequirements || ''
        const occupationMatch = specialRequirements.match(/职业：(.+)/)
        
        return {
          id: booking.id,
          code: bookingNumber,
          ticketType: '《永恒的高迪·圣家堂》VR沉浸体验',
          visitTime: `${bookingDate} ${formatTime(startTime)}-${formatTime(endTime)}`,
          visitorCount: 1,
          contactName: contactName,
          status: statusMap[booking.status] || 'confirmed',
          bookingData: {
            bookingInfo: {
              date: `${bookingDate.replace(/-/g, '年').replace(/年(\d{2})$/, '年$1日')} (${getWeekDay(bookingDate)})`,
              timeSlot: `${formatTime(startTime)}-${formatTime(endTime)}`,
              visitorCount: 1,
              bookingNumber: bookingNumber
            },
            visitorInfo: {
              name: contactName,
              phone: contactPhone,
              gender: genderMatch ? genderMatch[1] : '未填写',
              age: ageMatch ? ageMatch[1] : '未填写',
              education: educationMatch ? educationMatch[1] : '未填写',
              occupation: occupationMatch ? occupationMatch[1] : ''
            }
          }
        }
      })
      
      bookingRecords.value = bookings
      console.log('✅ 预约记录加载成功:', bookings.length, '条记录')
    } else {
      console.log('ℹ️ 暂无预约记录')
      bookingRecords.value = []
    }
  } catch (error) {
    console.error('❌ 加载预约记录失败:', error)
    bookingRecords.value = []
    // 不显示错误消息，避免影响用户体验
  }
}

// 获取星期几
const getWeekDay = (dateString) => {
  const date = new Date(dateString)
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weekdays[date.getDay()]
}

// 组件挂载时检查用户识别状态
onMounted(async () => {
  console.log('📱 预约系统页面加载，检查用户识别状态...')
  
  // 如果用户还未识别，触发识别流程
  if (!userStore.isIdentified.value) {
    showLoading('用户识别中', '正在识别您的设备信息，请稍候...')
    
    try {
      await userStore.initializeUser()
      const summary = userStore.getUserSummary()
      console.log('👤 用户识别完成:', summary)
      
      // 显示欢迎消息
      if (userStore.isNewUser.value) {
        console.log('🎉 欢迎新用户访问华南师范大学VR展馆！')
      } else {
        console.log(`👋 欢迎回来！这是您第${userStore.visitCount.value}次访问`)
      }
      
      // 加载用户预约记录
      await loadUserBookings()
      
    } catch (error) {
      console.error('用户识别失败:', error)
    } finally {
      hideLoading()
    }
  } else {
    console.log('✅ 用户已识别，Token:', userStore.userToken.value)
    
    // 更新访问信息
    userStore.updateVisitInfo()
    
    // 加载用户预约记录
    await loadUserBookings()
  }
})
</script>

<style scoped>
@import '../assets/css/system.css';
</style> 